//
//  PropStore.swift
//  HareMacro
//
//  Created by Entao on 2025/1/3.
//
import Foundation
import SwiftCompilerPlugin
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros

public struct PropStore: AccessorMacro {
    public static func expansion(
        of node: SwiftSyntax.AttributeSyntax, providingAccessorsOf declaration: some SwiftSyntax.DeclSyntaxProtocol, in context: some SwiftSyntaxMacros.MacroExpansionContext
    ) throws -> [SwiftSyntax.AccessorDeclSyntax] {

        guard let varName = declaration.variableName,
            let typeInfo = declaration.variableType
        else { fatalError("NO variable name found") }

        var userStore = "UserDefaults.standard"

        var missValue: String? = node.argument(label: "miss")
        if missValue == "nil" {
            missValue = nil
        }
        if let store = node.argument(label: "store") {
            if store.starts(with: ".") {
                userStore = "UserDefaults" + store
            } else if !store.isEmpty && store != "nil" {
                userStore = store
            }
        }
        var buf = ""
        //  \(typeInfo.optional ? (missValue == nil ? "" : " ?? " + missValue!) : "")
        if missValue == nil {
            buf = ""
        } else {
            buf = " ?? " + missValue!
        }
        let spec = declaration.variableSpecifier
        let a = """
            get{
                \(userStore).value(forKey:\(varName.quoted)) \( (typeInfo.optional || missValue != nil  ) ? "as?" : "as!") \(typeInfo.name) \(buf)
            }
            """
        let b = """
            set(newValue){
                \(userStore).setValue(newValue, forKey:\(varName.quoted) )
            }
            """
        if spec == "var" {
            return [AccessorDeclSyntax(stringLiteral: a), AccessorDeclSyntax(stringLiteral: b)]
        }
        fatalError("Only 'var' is support.")
    }

}
